<template>
    <div>
        {{ role.id? '修改角色权限' : '添加角色'}}
    </div>
    <el-card>
        <el-form :model="roleForm" :rules="rules" ref="formRef">
            <el-form-item label="角色名称" prop="name">
                <el-input v-model="roleForm.name" placeholder="请输入角色名称"></el-input>
            </el-form-item>

            <el-form-item label="权限配置" prop="permissions">
                <el-tree ref="treeRef" :default-checked-keys="isRoleList" :data="permissionTree" show-checkbox node-key="id" default-expand-all
                    :props="defaultProps"></el-tree>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="submitForm">提交</el-button>
                <el-button @click="resetForm">重置</el-button>
            </el-form-item>
        </el-form>

    </el-card>
</template>

<script setup lang='ts'>
import { ref, reactive } from 'vue';
import { ElMessage, ElTree, type FormInstance } from 'element-plus';
import { addRole, getRoleById, getRoleMenu, getRoles } from '@/apis/role/role';
import { buildTree } from '@/utils/treeUtil';
import type { RoleForm, RolesList } from '@/apis/role/type';
import Role from './Role.vue';
import router from '@/router';
import { useRoute } from 'vue-router';
import { tr } from 'element-plus/lib/locale/index.js';
const route = useRoute();
// 接受到的角色id
const role=ref<{id:number}>({
  id:route.params.id ? Number(route.params.id) :0,
})
// console.log(role.value.id);
// 查询选中的角色权限
let isRoleList = ref<number[]>([])
const getRolesID = async () => {

    if (role.value.id == 0) {
        return
    }

    let res = await getRoleById(role.value.id)
    console.log(res);
    roleForm.name = res.name
    // treeRef.value?.setChecked(res.menuIds,true,true)
    isRoleList.value = res.menuIds
};
getRolesID()


// 角色树数据类型
interface TreeNode {
    id: number;
    label: string;
    children: { id: number, label: string, children: { id: number, label: string }[] }[];
}

const permissionTree = ref<TreeNode[]>([]);

const getRolesList = async () => {
    let res = await getRoleMenu()
    // console.log('角色权限列表', res);
    let treeRolesList = buildTree(res.list)
    // console.log('角色权限树', treeRolesList);
    permissionTree.value = buildPermissionTree(treeRolesList);
    // console.log('aaaaa', permissionTree.value);
};
getRolesList()


// 封装树逻辑
function buildPermissionTree(rolesList: RolesList[]): TreeNode[] {
    // 遍历角色列表，为每个角色创建树节点
    return rolesList.map(role => ({
        id: role.id,
        label: role.name,
        // 为当前角色的子角色创建子节点，如果没有子角色，则默认为空数组
        children: (role.children || []).map(child => ({
            id: child.id,
            label: child.name,
            // 为子角色的孙子角色创建子节点，如果没有孙子角色，则默认为空数组
            children: (child.children || []).map(grandChild => ({
                id: grandChild.id,
                label: grandChild.name,
            })),
        })),
    }));
}



// 表单
const roleForm = reactive<RoleForm>({
    name: '',
    menuIds: [],
    id: 0
});

// 错误提示
const rules = {
    name: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
    ]
};


const defaultProps = {
    children: 'children',
    label: 'label',
};


const formRef = ref<FormInstance  | null>(null);
let treeRef = ref<InstanceType<typeof ElTree> | null>(null);
const submitForm = async () => {
    if (!formRef.value) {
        ElMessage.error('表单未正确初始化');
        return;
    }

    // 定义异步验证逻辑
    const handleValidation = async (valid: boolean) => {
        if (valid) {
            roleForm.menuIds =  treeRef.value?.getCheckedKeys() as number[];
            // roleForm.menuIds = isRoleList.value;
            console.log('55555555555',roleForm.menuIds,isRoleList.value);
            
            if(!roleForm.menuIds.length) return ElMessage.error('请选择权限');

            try {

                if(role.value.id){
                    roleForm.id = role.value.id;
                }
                await addRole(roleForm); // 调用后端接口提交数据
                router.push('/system/role');
                ElMessage.success(role.value.id?'角色修改成功':'角色添加成功');
                // console.log('提交的角色信息:', roleForm);
            } catch (error) {
                ElMessage.error(role.value.id?'角色添加失败，请稍后再试':'角色修改失败，请稍后再试');
                console.error('提交失败:', error);
            }
        } else {
            ElMessage.error('请检查表单填写是否正确');
        }
    };

    // 调用 validate 方法时，确保回调函数返回 void
    formRef.value.validate((valid) => {
        handleValidation(valid).catch((err) => {
            console.error('处理验证时发生错误:', err);
        });
    });
};


// 重置
const resetForm = () => {
    roleForm.name='',
    roleForm.menuIds=[]
}


</script>

<style scoped lang='less'></style>